package com.dwm716.shorturl.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author biliyu
 * @date 2024/8/1 13:22
 */

@Slf4j
public class IpShuDiUtil {

    private static final String URL = "https://ipinfo.io/widget/demo/";
    public static JSONObject getIpToAddress(String ip) {

        JSONObject resJson = new JSONObject();
//        try {
//            Document document = Jsoup.connect(URL + ip + "&action=2").get();
//            Elements es = document.select("script").eq(1);
//            for (Element e : es) {
//                String[] data = e.data().split("var");
//                for (String variable : data) {
//                    if (variable.contains("=") && variable.contains("ip_result")){
//                        String[] va = StringUtils.split(variable, "=");
//                        String value = va[1].trim().substring(0,va[1].trim().length() - 1);
//                        JSONObject object = JSONObject.parseObject(value);
//                        log.info(String.format("获取到的数据值:%s",value));
//                        resJson.put("address", object.getString("ASN归属地"));
//                    }
//                }
//            }
//        } catch (IOException ignored) {
//            log.error("获取失败");
//            resJson.put("address", "暂无");
////            throw new RuntimeException();
//        }

        // 获取 IP 地址
        try {
            log.info("当前 IP 是：" + ip);
            // 创建URL对象
            URL obj = new URL(URL + ip);
            // 打开连接
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            // 设置请求方法为GET
            con.setRequestMethod("GET");
            // 设置请求头
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            // 读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
//            log.info(response.toString());
            resJson.put("address", JSONObject.parseObject(String.valueOf(response)));
        } catch (Exception e) {
            log.error("获取失败");
            resJson.put("address", "{}");
        }

        return resJson;
    }

}
